//  This file is part of Swordbible - http://www.swordwarrior.net
//  Copyright (C) 2003-2009 Manu Mital mital.manu@gmail.com

//  This program is free software; you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation; either version 2, or (at your option)
//  any later version.

//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.

//  You should have received a copy of the GNU General Public License
//  along with this program; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.


// BottomPage.cpp : implementation file
//

#include <stdafx.h>
#include "SwordBible.h"
#include "SwordBibleDoc.h"
#include "BiblePage.h"
#include "BottomPage.h"
#include ".\bottompage.h"
#include "Search.h"
#include "BibleForm.h"


// CBottomPage dialog

int CBottomPage::staticPageCount = 0;  // number of pages created
CSwordBibleFonts CBottomPage::font;
CString CBottomPage::ActiveMainFrameCommand = _T("");
int CBottomPage::active = -1;


IMPLEMENT_DYNAMIC(CBottomPage, CPropertyPage)
CBottomPage::CBottomPage()
	: CPropertyPage(CBottomPage::IDD)
{
	staticPageCount++;				// increment the instance counter
	pModule = NULL;					// set pModule to point to NULL
	version = _T("");

	


	
}

CBottomPage::~CBottomPage()
{
	staticPageCount--;   // an instance of property page is destroyed

		
}

void CBottomPage::DoDataExchange(CDataExchange* pDX)
{
	CPropertyPage::DoDataExchange(pDX);

    DDX_Control(pDX, IDC_COMBO_BOTTOM_BOOK, m_cmbBibleBook);
	DDX_Control(pDX, IDC_COMBO_BOTTOM_CHAPTER, m_cmbBottomChapter);
	DDX_Control(pDX, IDC_COMBO_BOTTOM_VERSE, m_cmbBottomVerse);
	DDX_Control(pDX, IDC_RICHEDIT_BOTTOMPAGE, m_brichCtrl);
}


BEGIN_MESSAGE_MAP(CBottomPage, CPropertyPage)
	ON_WM_SIZE()
	ON_WM_CTLCOLOR()
	ON_COMMAND(ID_BOTTOM_COPY, OnBottomCopy)
    ON_COMMAND(ID_BOTTOM_SELECTALL, OnBottomSelectAll)
	ON_COMMAND(ID_BOTTOM_DISPLAY, OnBottomDisplay)
	ON_COMMAND(ID_BOTTOM_SEARCH, OnBottomSearch)
	ON_COMMAND(ID_BOTTOM_SYNCH, OnBottomSynch)
	ON_COMMAND(ID_BOTTOM_NEXT,OnNextChapter)
	ON_COMMAND(ID_BOTTOM_PREVIOUS,OnPreviousChapter)
  ON_COMMAND(ID_COMMENTARY_INFORMATION, OnInfo)
	ON_COMMAND(ID_BOTTOMPAGE_PRINT,OnPrint)
	ON_COMMAND(ID_BOTTOMPAGE_PRINTPREVIEW,OnPrintPreview)
	ON_COMMAND(ID_BOTTOM_ZOOM, OnZoom)
	ON_UPDATE_COMMAND_UI(ID_BOTTOM_ZOOM, OnUpdateZoom)

	ON_UPDATE_COMMAND_UI(ID_BOTTOM_SYNCH, OnUpdateBottomSynch)

	ON_COMMAND(ID_COMMENTARY_VERSIONS, OnShowVersions)	

	ON_MESSAGE(ID_COMMENTARY_COMMAND,OnMainFrameCommand)
	


	ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTW, 0, 0xFFFF, OnToolTipNotify)
    ON_NOTIFY_EX_RANGE(TTN_NEEDTEXTA, 0, 0xFFFF, OnToolTipNotify)   
   
	ON_CBN_SELCHANGE(IDC_COMBO_BOTTOM_BOOK, OnSelectBibleBook)
   ON_CBN_SELCHANGE(IDC_COMBO_BOTTOM_CHAPTER, OnSelectBibleChapter)
   ON_CBN_SELCHANGE(IDC_COMBO_BOTTOM_VERSE, OnSelectBibleVerse)
   ON_NOTIFY(EN_MSGFILTER, IDC_RICHEDIT_BOTTOMPAGE, OnEnMsgfilter)
   ON_WM_DESTROY()
 END_MESSAGE_MAP()






// CBottomPage message handlers
void CBottomPage::OnSize(UINT nType, int cx, int cy)
{
	CPropertyPage::OnSize(nType, cx, cy);

	CWnd* pWnd = GetDlgItem(IDC_RICHEDIT_BOTTOMPAGE);

	// resize the rich edit control
	if( ::IsWindow(pWnd ->GetSafeHwnd() )) 
	pWnd ->SetWindowPos(NULL,10,35,cx-20,cy-45,SWP_NOZORDER | SWP_NOACTIVATE);

	//resize and move the boxes that contain the bible book, chapter, verse
	if( ::IsWindow( m_cmbBibleBook.GetSafeHwnd() ))
		m_cmbBibleBook.SetWindowPos(NULL, 44, 8, 120,200,  SWP_NOZORDER | SWP_NOACTIVATE);

	if( ::IsWindow(m_cmbBottomChapter.GetSafeHwnd() ))
		m_cmbBottomChapter.SetWindowPos(NULL, 174, 8, 45, 200,  SWP_NOZORDER | SWP_NOACTIVATE);

	if( ::IsWindow(m_cmbBottomVerse.GetSafeHwnd() ))
		m_cmbBottomVerse.SetWindowPos(NULL, 224, 8, 45, 200,  SWP_NOZORDER | SWP_NOACTIVATE);
	

}

BOOL CBottomPage::OnInitDialog()
{
	CPropertyPage::OnInitDialog();

	if(CSwordBibleDoc::numComAvailable > 0) 
	{
		active = 0;
		pModule = CSwordBibleDoc::pRTFComModule[active];
	}
		

	// load the font of the page display
	font.location = AFX_BOTTOM; 
	font.Load();
	font.ConstructRTF();
	m_brichCtrl.SetBackgroundColor(FALSE, CColorMgr::RTFtoCOLORREF(font.bg_color) );


	//calculate the width and height of chars
	TEXTMETRIC tm;
	CClientDC dc(GetDlgItem(IDC_RICHEDIT_BOTTOMPAGE));
	dc.GetTextMetrics(&tm);
	font.text_cx = tm.tmAveCharWidth;
	font.text_cy = tm.tmHeight + tm.tmExternalLeading;

	// Enable tool tips
	EnableToolTips();   // enable tool tips for view



	/* Fill in the names of the Bible book in the Bible book combo */
	for( int i = 0; i < 66; i++)
	m_cmbBibleBook.AddString(CSwordBibleDoc::bookCode[i][0]);

	// set the selection to the current book
	m_cmbBibleBook.SetCurSel(CSwordBibleDoc::bottomBook() - 1);


	//find the number of chapters in the currently selected book and fill the combo box
	 oldChapCount =  _tstoi( CSwordBibleDoc::bookCode[m_cmbBibleBook.GetCurSel()][2] );
	 CString number;
	 for(int i = 0; i < oldChapCount; i++) {
		 number.Format(_T("%d"),i+1);			 
		 m_cmbBottomChapter.AddString(number);
	 }

	// set the chapter in the bottom module combo box
	 m_cmbBottomChapter.SetCurSel(CSwordBibleDoc::bottomChapter() - 1);	
	 m_cmbBottomChapter.LimitText(3);


 // get the total number of verses in the newly selected chapter
	oldVerseCount = CSwordBibleDoc::VerseCount[CSwordBibleDoc::bottomBook() - 1][ CSwordBibleDoc::bottomChapter() - 1 ];
	 
	
	 for(int i = 0; i < oldVerseCount; i++) {
		 number.Format(_T("%d"),i+1);			 
		 m_cmbBottomVerse.AddString(number);
	 }

	// set the verse in the bottom module's verse combo box
     m_cmbBottomVerse.SetCurSel(0);	
	 m_cmbBottomVerse.LimitText(3);
	
	
	// Show the chapter in the biblepage window
	ShowChapter();

	// to receive the mouseevents
	m_brichCtrl.SetEventMask(ENM_MOUSEEVENTS | ENM_KEYEVENTS | ENM_SCROLLEVENTS);
	m_brichCtrl.SendMessage(EM_EXLIMITTEXT,0,-1);


    if (!m_wndFormatBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD
       | WS_VISIBLE | CBRS_TOP |  CBRS_FLYBY | CBRS_TOOLTIPS) ||
       !m_wndFormatBar.LoadToolBar(IDR_BOTTOM_TOOLBAR))
   {
      TRACE0("Failed to create toolbar\n");
      return -1;      // fail to create
   }

   // buttons size: 16
   // bitmaps:
   // enabled - IDB_TOOLBAR_NORMAL
   // hovered - IDB_TOOLBAR_HOT
   // disabled - IDB_TOOLBAR_DISABLED
   // transparent color RGB(255, 0, 255)
   m_wndFormatBar.LoadTCToolBar(24, IDB_BITMAP_COMMENTARY,IDB_BITMAP_COMMENTARY,
                              IDB_BITMAP_COMMENTARY, RGB(255,255,255));




	// Position the control bars using RepositionBars. 
	RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0);

	// Expand the size of the Toolbar window so all controls in it would fit
	

	// Expand the size of the Toolbar window so all controls in it would fit	
	CRect toolBarRect;
	CToolBarCtrl& formatBar = m_wndFormatBar.GetToolBarCtrl();
	formatBar.GetWindowRect(toolBarRect);
	ScreenToClient(toolBarRect);
	toolBarRect.left = 10;
	toolBarRect.right += 600 ;
	formatBar.MoveWindow(toolBarRect,TRUE);

	
	

	return FALSE;  // return TRUE unless you set the focus to a control
	// EXCEPTION: OCX Property Pages should return FALSE
}

//  moves the background image of the title of the bottom page


HBRUSH CBottomPage::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CPropertyPage::OnCtlColor(pDC, pWnd, nCtlColor);

	
	// TODO:  Return a different brush if the default is not desired
	return hbr;
}

BOOL CBottomPage::OnSetActive()
{
	// TODO: Add your specialized code here and/or call the base class

	if(CSwordBibleDoc::bottomSynch)
			CSwordBibleDoc::curBottomKey = CSwordBibleDoc::key;

	int Book = CSwordBibleDoc::bottomBook() - 1;
	int Chapter = CSwordBibleDoc::bottomChapter() - 1;
	int Verse = CSwordBibleDoc::bottomVerse() - 1;

	m_cmbBibleBook.SetCurSel(Book);
	OnSelectBibleBook();

	m_cmbBottomChapter.SetCurSel(Chapter);
	OnSelectBibleChapter(); 

	m_cmbBottomVerse.SetCurSel(Verse);
	OnSelectBibleVerse(); 

    return CPropertyPage::OnSetActive();
}



// Displays the relevant chapter text in the bottom window
void CBottomPage::ShowChapter(void)
{
	
	// the current verse of the bible that is active
	sword::VerseKey key = CSwordBibleDoc::curBottomKey;

	if (!pModule) return;   // check that pointer is not NULL

	
		char buf[4];
		int chap = key.Chapter();
		_itoa(chap, buf, 10);

		 CString chapText = font.GetHeaderRTF();

		CString titleSize;
		titleSize.Format(_T("\\cf2\\fs%d"), font.text_facesize + 5);
		chapText = chapText +  titleSize + (CString) key.getBookName()+ _T(" ") + buf + _T(" (") + (CString) pModule->Description()
			+ _T(") ");
		
	

		// reset the font size
		titleSize.Format(_T("\\fs%d"), font.text_facesize);
		chapText = chapText +  titleSize;

	    pModule->SetKey(CSwordBibleDoc::curBottomKey); 

		
		chapText = chapText +  _T("\\par ") + (CString) pModule->RenderText() + _T("}"); 

		if(CSwordBibleDoc::crossref_tags)
		{
		chapText.Replace(_T("<a href=\"\">"),  _T("<a href=\"\">\\cf6\\b "));
		chapText.Replace(_T("</a>"), _T("</a>\\cf2\\b0 "));
		}

		else
		{
		chapText.Replace(_T("<a href=\"\">"), _T(""));
		chapText.Replace(_T("</a>"), _T(""));
		}


		// display the collected text	
		m_brichCtrl.SetRTF(chapText);

			ZoomText();

        // create a new database of tips
		tips.Clear();
		if(CSwordBibleDoc::crossref_tags) CreateTips();
	

	
		
}

void CBottomPage::OnShowVersions()
{
	RECT rc;
    m_wndFormatBar.GetToolBarCtrl().GetItemRect(0,&rc);
	m_wndFormatBar.ClientToScreen(&rc); // TrackPopupMenu uses screen coords

   CMenu menu;
   menu.CreatePopupMenu();
   CMenu* pPopup = NULL;
   pPopup = &menu;

   if(pPopup == NULL) return;
   int dwSelectionMade;  

 
   // fill in the strings for different commentary versions
	for(int i = 0; i < CSwordBibleDoc::numComAvailable; i++)
		if(CSwordBibleDoc::pRTFComModule[i] != NULL)
		{
			         pPopup->AppendMenu(MF_STRING,ID_COMVERSION_NAMES + i, (CString) CSwordBibleDoc::pRTFComModule[i]->Description());
					 if(active == i) pPopup->CheckMenuItem(ID_COMVERSION_NAMES + i,MF_CHECKED); 

		}


         dwSelectionMade =  pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_LEFTBUTTON|TPM_RETURNCMD, 
         rc.left, rc.bottom + 4, this);

	
		int selection = dwSelectionMade;
		int base = ID_COMVERSION_NAMES;
		int temp = selection - base;


	if(temp >= 0 && temp < CSwordBibleDoc::numComAvailable) 
	{
		 active = temp;
	     pModule = CSwordBibleDoc::pRTFComModule[active];
	     ShowChapter();
	
	}

    pPopup->DestroyMenu(); 


}


void CBottomPage::CreateTips()
{
	FINDTEXTEX ft1, ft2;
	ft1.chrg.cpMin = 0;
	ft1.chrg.cpMax = -1;
	ft1.lpstrText =  _T("<a href=\"\">");

	ft2.chrg.cpMin = 0;
	ft2.chrg.cpMax = -1;
	ft2.lpstrText = _T("</a>");

	int start = 0;
	int end = 0;


	while (true) {

	
	start = m_brichCtrl.FindText(FR_DOWN , &ft1); //find the href start tags  
	end = m_brichCtrl.FindText(FR_DOWN , &ft2); //find the href tags  

	if(start == -1 || end == -1) return;

	CString ref = _T("");
	m_brichCtrl.GetTextRange(start + 11, end, ref);

	tips.Add(start, end - 11, ref);

	
	ft1.chrg.cpMin = start;
	ft2.chrg.cpMin = start;

	m_brichCtrl.SetSel(end, end + 4);
	m_brichCtrl.ReplaceSel(_T(""));

	m_brichCtrl.SetSel(start,start + 11);
	m_brichCtrl.ReplaceSel(_T(""));

	}


}


void CBottomPage::OnBottomCopy(void) 
{
	// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

  m_brichCtrl.Copy();

}


void CBottomPage::OnBottomSelectAll(void)
{
	// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

  m_brichCtrl.SetSel(0,-1);

}


void CBottomPage::OnBottomDisplay(void)
{

	// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;

	 CColorMgr colordlg(NULL, &font);

   if(colordlg.DoModal() == IDOK)
  	 
  {
	  m_brichCtrl.SetBackgroundColor(false, CColorMgr::RTFtoCOLORREF(font.bg_color) );
	  ShowChapter();
  }

	
}


void CBottomPage::OnBottomSearch(void)
{
	// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   == this)
	  CBiblePage::OnRightClickSearch(this, AFX_COMMENTARY, active, _T("type search words here")); 
  
}

void CBottomPage::OnBottomSynch() 
{

		// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;

	CSwordBibleDoc::bottomSynch  =  !(CSwordBibleDoc::bottomSynch);
	AfxGetApp()->WriteProfileInt(_T("Bottom"),_T("Synchronize"),CSwordBibleDoc::bottomSynch);

	if(CSwordBibleDoc::bottomSynch) BibleSynch();
	
}

void CBottomPage::OnUpdateBottomSynch(CCmdUI* pCmdUI) 
{
		// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;


	if(CSwordBibleDoc::bottomSynch == TRUE)
		pCmdUI->SetCheck(1);

	else if (CSwordBibleDoc::bottomSynch == FALSE)
		pCmdUI->SetCheck(0);
	
}

void CBottomPage::OnNextChapter()
{

	// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;

	
	sword::VerseKey temp = CSwordBibleDoc::curBottomKey;
	temp.Chapter( temp.Chapter() + 1);
	if(temp.Error() ) return;

	CSwordBibleDoc::curBottomKey = temp;

	int Book = CSwordBibleDoc::bottomBook() - 1;
	int Chapter = CSwordBibleDoc::bottomChapter() - 1;

	m_cmbBibleBook.SetCurSel(Book);
	OnSelectBibleBook();

	m_cmbBottomChapter.SetCurSel(Chapter);
	OnSelectBibleChapter(); 

	
}


void CBottomPage::OnPreviousChapter()
{

	// only the active page should handle the message
  if(     ((CPropertySheet*) GetParent())->GetActivePage()   != this) return;


	sword::VerseKey temp = CSwordBibleDoc::curBottomKey;
	temp.Chapter( temp.Chapter() - 1);
	if(temp.Error() ) return;

	CSwordBibleDoc::curBottomKey = temp;

	int Book = CSwordBibleDoc::bottomBook() - 1;
	int Chapter = CSwordBibleDoc::bottomChapter() - 1;

	m_cmbBibleBook.SetCurSel(Book);
	OnSelectBibleBook();

	m_cmbBottomChapter.SetCurSel(Chapter);
	OnSelectBibleChapter(); 
	


}

void CBottomPage::OnInfo()
{
  if (!pModule) return;   // check that pointer is not NULL

  // clear limits
	tips.Clear();

  CString info = font.GetHeaderRTF();
  info +=  pModule->getConfigEntry("About") ;

  info += _T("}");

  m_brichCtrl.SetRTF(info);

  
}

BOOL CBottomPage::OnToolTipNotify(UINT id, NMHDR *pNMHDR,   LRESULT *pResult)
{
	
   ASSERT(pNMHDR->code == TTN_NEEDTEXTA || pNMHDR->code == TTN_NEEDTEXTW);

     // if there is a top level routing frame then let it handle the message
     if (GetRoutingFrame() != NULL) return FALSE;

     // to be thorough we will need to handle UNICODE versions of the message also !!
     TOOLTIPTEXTA* pTTTA = (TOOLTIPTEXTA*)pNMHDR;
     TOOLTIPTEXTW* pTTTW = (TOOLTIPTEXTW*)pNMHDR;
     TCHAR szFullText[512];
     CString strTipText;
     UINT nID = pNMHDR->idFrom;

     if (pNMHDR->code == TTN_NEEDTEXTA && (pTTTA->uFlags & TTF_IDISHWND) ||
         pNMHDR->code == TTN_NEEDTEXTW && (pTTTW->uFlags & TTF_IDISHWND))
     {
          // idFrom is actually the HWND of the tool 
          nID = ::GetDlgCtrlID((HWND)nID);
     }

     if (nID != 0) // will be zero on a separator
     {
          AfxLoadString(nID, szFullText);
          strTipText=szFullText;

#ifndef _UNICODE
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               lstrcpyn(pTTTA->szText, strTipText, sizeof(pTTTA->szText));
          }
          else
          {
               _mbstowcsz(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#else
          if (pNMHDR->code == TTN_NEEDTEXTA)
          {
               _wcstombsz(pTTTA->szText, strTipText,sizeof(pTTTA->szText));
          }
          else
          {
               lstrcpyn(pTTTW->szText, strTipText, sizeof(pTTTW->szText));
          }
#endif

          *pResult = 0;

          // bring the tooltip window above other popup windows
          ::SetWindowPos(pNMHDR->hwndFrom, HWND_TOP, 0, 0, 0, 0,SWP_NOACTIVATE|
               SWP_NOSIZE|SWP_NOMOVE|SWP_NOOWNERZORDER); return TRUE;
     }
      return FALSE;
}


// this function is called when the user selects a book of the bible from
// the combo box
void CBottomPage::OnSelectBibleBook()
{
	// the 0 based index of the new book that the user has selected
	int selectedBook  = m_cmbBibleBook.GetCurSel();

	// change the active bible book for the bottom section
	CSwordBibleDoc::curBottomKey  = (CStringA) (CSwordBibleDoc::bookCode[selectedBook][0] + _T(" 1:1"));
	        

	// empty the strings in the chapter combo box of the bottom section of application
	for(int ni = 0; ni < oldChapCount ; ni++)
	m_cmbBottomChapter.DeleteString(0);


    // get the total number of chapters in the newly selected book
	int totalChap = _tstoi(CSwordBibleDoc::bookCode[selectedBook][2]);

   // add the "chapter number" strings in the chapter combo box of the notes
	CString indexString;
	for(int nni = 0; nni < totalChap ; nni++)  // nni = new notes index
	{ 
		indexString.Format(_T("%d"),nni + 1);
		m_cmbBottomChapter.AddString(indexString);
	}
	
	oldChapCount = totalChap;

	// when a new book of the bible is selected, the chapter and verses default to 1
	m_cmbBottomChapter.SetCurSel(0);
	OnSelectBibleChapter();
	
}






// synchronize the book/chapter of the commentaries with the current
// book/chapter of the main bible
void CBottomPage::BibleSynch()
{
	// only the active page should handle the message
	  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

	int Book = CSwordBibleDoc::Book()  - 1;
	int Chapter = CSwordBibleDoc::Chapter() - 1;
	int Verse = CSwordBibleDoc::Verse() - 1;

	m_cmbBibleBook.SetCurSel(Book);
	OnSelectBibleBook();

	m_cmbBottomChapter.SetCurSel(Chapter);
	OnSelectBibleChapter();

	m_cmbBottomVerse.SetCurSel(Verse);
	OnSelectBibleVerse();

}

void CBottomPage::OnSelectBibleChapter()
{

	// the newly selected chapter from the notes combo box
	int selectedChapter  = m_cmbBottomChapter.GetCurSel();

	// change the record in the document class
	CString newKey;
	newKey.Format(_T("%s %d:%d"),CSwordBibleDoc::bookCode[CSwordBibleDoc::bottomBook()-1][0],selectedChapter + 1, 1);
	CSwordBibleDoc::curBottomKey =  (CStringA) newKey;

 
	// empty the strings in the verse combo box of the bottom section of application
	for(int ni = 0; ni < oldVerseCount ; ni++)
	m_cmbBottomVerse.DeleteString(0);


    // get the total number of verses in the newly selected chapter
	int totalVerses = CSwordBibleDoc::VerseCount[   CSwordBibleDoc::bottomBook() - 1][ CSwordBibleDoc::bottomChapter() - 1 ];


   // add the "Verse number" strings in the Verse combo box
	CString indexString;
	for(int nni = 0; nni < totalVerses ; nni++)  // nni = new notes index
	{ 
		indexString.Format(_T("%d"),nni + 1);
		m_cmbBottomVerse.AddString(indexString);
	}

	// set the oldVerseCount to the number of verses in the current chapter of the bible in the 
	// notes section. This variable is used later during the deletion of the strings.
	oldVerseCount = totalVerses;

	m_cmbBottomVerse.SetCurSel(0);
	OnSelectBibleVerse();

	

}

void CBottomPage::OnSelectBibleVerse()
{
	// the newly selected verse from the combo box
	int selectedVerse = m_cmbBottomVerse.GetCurSel();

	// change the record in the document class
	CString newKey;
	newKey.Format(_T("%s %d:%d"),CSwordBibleDoc::bookCode[CSwordBibleDoc::bottomBook()-1][0],
		CSwordBibleDoc::bottomChapter() , selectedVerse + 1);

	CSwordBibleDoc::curBottomKey =  (CStringA) newKey;

	ShowChapter();
	
}



void CBottomPage::OnPrint()
{
		// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;
  
	
	CBibleForm::pControl = (CRichEditCtrl *) GetDlgItem(IDC_RICHEDIT_BOTTOMPAGE);
	AfxGetMainWnd()->SendMessageToDescendants(WM_PRINT_CONTROL, (WPARAM) 1 , 0);
    

}


void CBottomPage::OnPrintPreview()
{
		// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;

//  m_brichCtrl.PrintPreviewRTF();


 }


void CBottomPage::OnZoom()
{
	// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;


	CSwordBibleDoc::bottomZoom = !(CSwordBibleDoc::bottomZoom);

	ZoomText();

}

void CBottomPage::OnUpdateZoom(CCmdUI *pCmdUI)
{

	// only the active page should handle the message
   if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return;


	pCmdUI->SetCheck(CSwordBibleDoc::bottomZoom);
	
}

void CBottomPage::ZoomText()
{
	if(CSwordBibleDoc::bottomZoom) m_brichCtrl.SendMessage(EM_SETZOOM, 5,4); //zoom by 1.25
	else m_brichCtrl.SendMessage(EM_SETZOOM, 0,0);  // turn off zooming

	
}


LONG CBottomPage::OnMainFrameCommand(UINT, LONG)
{
	// only the active page should handle the message
  if(  !( ((CPropertySheet*) GetParent())->GetActivePage()   == this) )  
	  return 0L;


	 if(ActiveMainFrameCommand == _T("print")) OnPrint();
	 else if(ActiveMainFrameCommand == _T("BibleSynch")) BibleSynch();
	 else if(ActiveMainFrameCommand == _T("synch")) OnBottomSynch();
	 else if (ActiveMainFrameCommand == _T("copy")) OnBottomCopy();
	 else if (ActiveMainFrameCommand == _T("selectall")) OnBottomSelectAll();
	 else if (ActiveMainFrameCommand == _T("display")) OnBottomDisplay();
	 else if (ActiveMainFrameCommand == _T("zoom")) OnZoom();
   else if (ActiveMainFrameCommand == _T("search")) OnBottomSearch();
	 else if (ActiveMainFrameCommand == _T("previous")) OnPreviousChapter();
	 else if (ActiveMainFrameCommand == _T("next")) OnNextChapter();
   else if(ActiveMainFrameCommand == _T("info")) OnInfo();
			
		return 0L;
}




void CBottomPage::OnEnMsgfilter(NMHDR *pNMHDR, LRESULT *pResult)
{
	MSGFILTER *pMsgFilter = reinterpret_cast<MSGFILTER *>(pNMHDR);
	// TODO:  The control will not send this notification unless you override the
	// CPropertyPage::OnInitDialog() function to send the EM_SETEVENTMASK message
	// to the control with either the ENM_KEYEVENTS or ENM_MOUSEEVENTS flag 
	// ORed into the lParam mask.

	if(pMsgFilter->msg == WM_MOUSEMOVE)
	{ 
		CPoint point;                                            
        ::GetCursorPos(&point); //where is the mouse?


		 // change the coordinates of the point from Screen to that of richedit
		m_brichCtrl.ScreenToClient(&point);

		int nchar =  m_brichCtrl.CharFromPos(point);

		CString keylist = _T("");
		int lower = 0, upper = 0;
		if(tips.FromPos(nchar,lower, upper, keylist) == TRUE) 
		SetCursor(CBibleSheet::m_hHandCursor);
	}
	

	if(pMsgFilter->msg == WM_LBUTTONDOWN )
	{ 
		
		 CPoint point;                                            
     ::GetCursorPos(&point); //where is the mouse?

		 // change the coordinates of the point from Screen to that of richedit
		m_brichCtrl.ScreenToClient(&point);

		int nchar =  m_brichCtrl.CharFromPos(point);

		CString keyList = _T("");
		int lower = 0, upper = 0;
		if(tips.FromPos(nchar,lower, upper, keyList) == FALSE) 
		{
			return;     // no tooltip to display
		}

		keyList.Replace(_T(','),_T(';'));

	  CString tip;

    CBiblePage::DisplayReferenceVerses(keyList, tip);

    CBibleSheet::DisplayReference(_T("Scripture Cross-reference"), tip);	


	}


	else if (pMsgFilter->msg == WM_RBUTTONDOWN)   OnRightButtonDown();

	*pResult = 0;
}


void CBottomPage::OnRightButtonDown()
{

	 CPoint point;                                            
     ::GetCursorPos(&point); //where is the mouse?
     CMenu menu; //lets display out context menu :) 
     DWORD dwSelectionMade;                                       
     VERIFY(menu.LoadMenu(IDR_MENU_BOTTOM) );  
     CMenu *pmenuPopup = menu.GetSubMenu(0);
     ASSERT(pmenuPopup != NULL);   

	 if(CSwordBibleDoc::bottomZoom)	pmenuPopup->CheckMenuItem(ID_COMMENTARY_ZOOMTEXT,MF_CHECKED); 
	 if(CSwordBibleDoc::bottomSynch)	pmenuPopup->CheckMenuItem(ID_COMMENTARY_SYNCHRONIZE,MF_CHECKED); 


	   // get the word under mouse
	  CPoint pt = point;
	  m_brichCtrl.ScreenToClient(&pt);     // change the coordinates of the point from Screen to that of richedit
	  CString text = _T("");
    CBiblePage::GetWordUnderMouse(&m_brichCtrl, pt, text);   

    CString ltext = _T("Lookup: ");
    CString stext = _T("Search for: ");

	  if(text.GetLength() > 1) {
		  ltext += text;
		  pmenuPopup->ModifyMenu(0, MF_BYPOSITION|MF_STRING, ID_COM_DICT_LOOKUP, ltext);

		  stext += text;
		  pmenuPopup->ModifyMenu(1, MF_BYPOSITION|MF_STRING, ID_COM_SEARCH, stext);

	  }


     dwSelectionMade = pmenuPopup->TrackPopupMenu( (TPM_LEFTALIGN|TPM_LEFTBUTTON|
                                                      TPM_RETURNCMD),
                                                    point.x, point.y, this); 

	

	
	switch (dwSelectionMade)
	{
	case ID_COM_SEARCH:                 CBiblePage::OnRightClickSearch(this, AFX_COMMENTARY, active, text); break;
  case ID_COM_DICT_LOOKUP:            CBiblePage::OnLookupDict(text); break;
	case ID_COMMENTARY_PRINT:		        OnPrint(); break;
	case ID_COMMENTARY_COPY:			      OnBottomCopy(); break;
	case ID_COMMENTARY_SELECTALL:       OnBottomSelectAll(); break;
	case ID_BOTTOM_DISPLAY:				      OnBottomDisplay(); break;    
	case ID_COMMENTARY_ZOOMTEXT:        OnZoom(); break; 
	case ID_BOTTOM_SEARCH:              OnBottomSearch(); break;
	case ID_COMMENTARY_PREVIOUSCHAPTER: OnPreviousChapter(); break;
	case ID_COMMENTARY_NEXTCHAPTER:     OnNextChapter(); break;
  case ID_COMMENTARY_INFORMATION:     OnInfo(); break;

	}
	pmenuPopup->DestroyMenu(); 
}



void CBottomPage::OnDestroy()
{
	CPropertyPage::OnDestroy();
}

